import type { Sample, SampleGroup, BackendPaginatedResponse, GroupedPaginatedResponse } from "@/types"

// 将后端扁平数据转换为前端分组格式
export function transformToGroupedData(
    backendData: BackendPaginatedResponse<Sample>,
    status: "unassigned" | "mixed-only" | "completed",
): GroupedPaginatedResponse {
    const { dataList, total, page, pageSize, totalSamples } = backendData

    const groups: SampleGroup[] = []

    if (status === "unassigned") {
        // 未分配状态：每个样品单独一组
        dataList.forEach((sample) => {
            groups.push({
                id: sample.id,
                type: "unassigned",
                samples: [sample],
            })
        })
    } else if (status === "mixed-only") {
        // 仅混合编号状态：按mixedNumber分组
        const mixedGroups = new Map<string, Sample[]>()

        dataList.forEach((sample) => {
            if (sample.mixedNumber && !sample.samplingNumber) {
                if (!mixedGroups.has(sample.mixedNumber)) {
                    mixedGroups.set(sample.mixedNumber, [])
                }
                mixedGroups.get(sample.mixedNumber)!.push(sample)
            }
        })

        mixedGroups.forEach((samples, mixedNumber) => {
            groups.push({
                id: mixedNumber,
                type: "mixed-only",
                mixedNumber,
                samples,
            })
        })
    } else if (status === "completed") {
        // 完成状态：按samplingNumber分组
        const samplingGroups = new Map<string, Sample[]>()

        dataList.forEach((sample) => {
            if (sample.samplingNumber) {
                if (!samplingGroups.has(sample.samplingNumber)) {
                    samplingGroups.set(sample.samplingNumber, [])
                }
                samplingGroups.get(sample.samplingNumber)!.push(sample)
            }
        })

        samplingGroups.forEach((samples, samplingNumber) => {
            groups.push({
                id: samplingNumber,
                type: "complete",
                samplingNumber,
                samples,
            })
        })
    }

    // 计算总页数
    const totalPages = Math.ceil(total / pageSize)

    return {
        groups,
        total,
        page,
        pageSize,
        totalPages,
        totalSamples,
    }
}
